﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using OgilvyOne.BLL;
using OgilvyOne.Model;
using System.Collections;
using ECCIT;
using ECCIT.Web;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.BLL;
using OgilvyOne.UKNow.Configuration;
using System.Data;
using System.IO;

public partial class admin_UKNOW_event_event_add : AdminBasePage
{
    private const string VIEWSTATE_COLUMN_ID = "columnid";
    private const string VIEWSTATE_LAYER_ID = "layerid";
    private const string VIEWSTATE_EVENT_ID = "eid";
    private const string VIEWSTATE_IMG_LIST = "img_list";
    private const string VIEWSTATE_IMG_TOP = "img_top";
    private const string VIEWSTATE_IMG_VENUE = "img_venue";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string isSpecial = Request.QueryString["IsSpecial"];
            if (isSpecial == "1")
                this.htmlUpLoad.Visible = true;
            ViewState[VIEWSTATE_COLUMN_ID] = int.Parse(Request.Params[VIEWSTATE_COLUMN_ID]);
            ViewState[VIEWSTATE_LAYER_ID] = Request.Params[VIEWSTATE_LAYER_ID];

            string sEventsID = RequestContext.GetParamValueByParamName(VIEWSTATE_EVENT_ID, "");
            ViewState[VIEWSTATE_EVENT_ID] = sEventsID;
            ViewState[VIEWSTATE_IMG_LIST] = "";
            ViewState[VIEWSTATE_IMG_TOP] = "";
            ViewState[VIEWSTATE_IMG_VENUE] = "";
            RegisterHiddenField("hdnLangID", this.LangID.ToString());

            if (string.IsNullOrEmpty(sEventsID))
                InitPage(null, 0);
            else
                InitPage(int.Parse(sEventsID), 0);
         

        }
    }

    private void InitPage(int? eventsID, int type)
    {
        InitControls();

        EventsModel model = null;
        if (eventsID.HasValue)
        {
            EventsBLL bll = new EventsBLL(this.LangID);
            model = bll.selEvent(eventsID.Value);
        }

        BindEventsToControls(model, type);
    }

    private void BindEventsToControls(EventsModel info, int type)
    {

        if (ViewState[VIEWSTATE_EVENT_ID]=="")
        {
            infoname.Text = "新增活动";

            if (info == null)
            { return; }
        }
        else
        {
            infoname.Text = "修改活动";
        }

        title.Text = info.Title;
        txtSubTitle.Text = info.SubTitle;
        area_ddl.SelectedValue = (info.City.HasValue) ? info.City.Value.ToString() : "";
        address_txt.Text = info.Venue;
        art_ddl.SelectedValue = (info.ArtFormID.HasValue) ? info.ArtFormID.ToString() : "";
        phoneEvent.Text = info.EventPhone;   //手机活动标题
        string sStartTime = (info.StartTime.HasValue) ? info.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
        if (sStartTime.EndsWith(" 00:00:00")) sStartTime = sStartTime.Substring(0, 10);
        txtStartTime.Text = sStartTime;

        string sEndTime = (info.EndTime.HasValue) ? info.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
        if (sEndTime.EndsWith(" 00:00:00")) sEndTime = sEndTime.Substring(0, 10);
        txtEndTime.Text = sEndTime;
        sponsors_ddl.SelectedValue = (info.SponsorID.HasValue) ? info.SponsorID.ToString() : "";

        txtShowTime.Text = info.ShowTime == null ? "" : info.ShowTime;
        summary_txt.Text = info.ShortDescription;
        ///Region
        ///新增编辑字段,活动手机内容
        ///修改人  穆凤凤
        ///修改时间 2012-4-26
        ///endRegion
        PhoneDetail.Text = info.PhoneDetail;//mff
        content.Text = info.Detail;
        ///Region
        ///新增编辑字段,巡回/教育活动
        ///修改人  穆凤凤
        ///修改时间 2012-4-10
        ///endRegion
        Education.Text = info.Education;
        ///Region
        ///新增编辑字段,活动的显示顺序
        ///修改人  穆凤凤
        ///修改时间 2012-3-29
        ///endRegion
        TextBox_order.Text = info.Order.ToString();//mff
        hot_rbt.SelectedValue = info.IsHot ? "1" : "0";
        recom_rbt.SelectedValue = info.IsRecommendation ? "1" : "0";
        indextop.SelectedValue = info.IsHomepageTop ? "1" : "0";
        columntop.SelectedValue = info.IsColumnTop ? "1" : "0";
        pub.SelectedValue = info.State.ToString();
        templateId.SelectedValue = (info.TemplateID.HasValue) ? info.TemplateID.Value.ToString() : "";
        labLng.Text = info.Lng;
        labLat.Text = info.Lat;
        txtTicketUrl.Text = info.TicketUrl;
        chkIsSeriesMain.Checked = (type==0) ? info.IsSeriesMain : false;
        ddlSeries.SelectedValue = (info.SeriesMainEventsID.HasValue) ? info.SeriesMainEventsID.Value.ToString() : "";
        chkAllowUpload.Checked = (info.AllowUploadAttachToComment.HasValue) ? info.AllowUploadAttachToComment.Value : false;
        txtPhoneVenue.Text = info.PhoneVenue;     //为手机活动地点赋值

        if (!string.IsNullOrEmpty(info.Week))
        {
            JoinedString str = new JoinedString(info.Week, ",");
            if (str.Contains("1")) Monday.Checked = true;
            if (str.Contains("2")) Tuesday.Checked = true;
            if (str.Contains("3")) Wednesday.Checked = true;
            if (str.Contains("4")) Thursday.Checked = true;
            if (str.Contains("5")) Friday.Checked = true;
            if (str.Contains("6")) Saturday.Checked = true;
            if (str.Contains("7")) Sunday.Checked = true;
        }
             
        //将图片路径保存在ViewState里面，用于在没有修改图片的情况下保存数据的时候从ViewState里面将原来的图片路径取出来保存到数据库
        ViewState[VIEWSTATE_IMG_LIST] = info.ListImg;
        ViewState[VIEWSTATE_IMG_TOP] = info.TopImg;
        ViewState[VIEWSTATE_IMG_VENUE] = info.VenueImagePath;
    }

    private void InitControls()
    {
        
        //获取字典里的活动城市
        this.area_ddl.Items.Clear();
        DataSet ds = new DictionaryManageBLL().GetDictionary(" upid = '208' order by cnname");
        //2012-5-21 新增加的全部城市 李学明 确定不要了
        //this.area_ddl.Items.Add(new ListItem(this.LangID==1033?"All City":"全部", "-1"));
        for (int i = 0; i < ds.Tables.Count; i++)
        {
            DataTable table = ds.Tables[i];
            foreach (DataRow row in table.Rows)
            {
                this.area_ddl.Items.Add(new ListItem(row["cnname"].ToString(), row["CID"].ToString()));
            }
        }

        //获取 活动的艺术形式
        this.art_ddl.Items.Clear();
        IList<ArtFormModel> Artlist = new ArtFormBLL(LangID).SelectArtForms();
        foreach (ArtFormModel art in Artlist)
        {
            this.art_ddl.Items.Add(new ListItem(art.Name, art.ID.ToString()));
        }

        //获取赞助商
        this.sponsors_ddl.Items.Clear();
        this.sponsors_ddl.Items.Add(new ListItem("无", ""));

        IList<SponsorModel> Sponsorlist = new SponsorBLL(LangID).selectSponsor();//mff
        foreach (SponsorModel spon in Sponsorlist)
        {
            this.sponsors_ddl.Items.Add(new ListItem(spon.Name, spon.ID.ToString()));
        }

        //初始模板
        this.templateId.Items.Clear();
        ModelManageBLL mmb = new ModelManageBLL();
        DataSet temdata = mmb.GetModel("");
        for (int i = 0; i < temdata.Tables.Count; i++)
        {
            DataTable table = temdata.Tables[i];
            for (int j = 0; j < table.Rows.Count; j++)
            {
                DataRow row = table.Rows[j];

                this.templateId.Items.Add(new ListItem(row["tem_name"].ToString(), row["tem_id"].ToString()));

            }
        }

        // 获取系列活动数据
        this.ddlSeries.Items.Clear();
        IList<EventsModel> events = new EventsBLL(this.LangID).GetSeriesMainEvents();
        ddlSeries.Items.Add(new ListItem("--请选择--", ""));
        foreach (EventsModel evt in events)
            ddlSeries.Items.Add(new ListItem(evt.Title, evt.ID.ToString()));
    }

    protected void Sub_click(object sender, EventArgs e)
    {
        EventsBLL bll = new EventsBLL(this.LangID);
        EventDateBLL eDBll=new EventDateBLL(this.LangID);
        EventsModel info = new EventsModel();
        

        string filename = "";
        string topImgName = "";
        string venueMapFileName = null;
        string upLoadHtmlName = null;
        string path = Server.MapPath("~/uploadfiles/image/");
        
        //列表图上传
        ResultInfo res1 = UploadedFile.Save(file, ConfigCacheManager.FilePath.UploadImagePath, UploadedFile.RenameHandlers.RenameToGuid);
        if (res1.Result) filename = ((FileInfo)res1.ReturnObject).Name;
        
        //置顶图上传
        ResultInfo res2 = UploadedFile.Save(filetop, ConfigCacheManager.FilePath.UploadImagePath, UploadedFile.RenameHandlers.RenameToGuid);
        if (res2.Result) topImgName = ((FileInfo)res2.ReturnObject).Name;

        //活动举办地点地图上传
        ResultInfo res3 = UploadedFile.Save(fileVenueMap, ConfigCacheManager.FilePath.UploadImagePath, UploadedFile.RenameHandlers.RenameToGuid);
        if (res3.Result) venueMapFileName = ((FileInfo)res3.ReturnObject).Name;

        //特色活动文件上传
        ResultInfo resu=UploadedFile.Save(fileHtml, ConfigCacheManager.FilePath.UploadHtmlPath, UploadedFile.RenameHandlers.RenameToGuid);
        if (resu.ReturnObject != null)
            upLoadHtmlName = ((FileInfo)resu.ReturnObject).Name;
        info.ID = null;
        if (!string.IsNullOrEmpty(ViewState[VIEWSTATE_EVENT_ID].ToString()))
           info.ID = int.Parse(ViewState[VIEWSTATE_EVENT_ID].ToString());

        info.Title = title.Text;
        info.SubTitle = txtSubTitle.Text;
        
        info.LanguageID = LangID;
        info.City = int.Parse(area_ddl.SelectedValue);
        info.Venue = address_txt.Text;
        info.ArtFormID = int.Parse(art_ddl.SelectedValue);
        bool isok = true;
        string erro = "";
        try
        {
            info.Lng = labLng.Text;
            info.Lat = labLat.Text;
        }
        catch (Exception)
        {
            erro = "请为地理坐标提供有效值";
            isok = false;
        }
       
        
       
        info.StartTime = null;
        info.EndTime = null;
        DateTime startTime, endTime;
        if (DateTime.TryParse(txtStartTime.Text, out startTime))
            info.StartTime = startTime;

        if (DateTime.TryParse(txtEndTime.Text, out endTime))
            info.EndTime = endTime;

        info.SponsorID = null;
        if (sponsors_ddl.SelectedValue != string.Empty)
            info.SponsorID = int.Parse(sponsors_ddl.SelectedValue);

        info.ShortDescription = summary_txt.Text;
        ///Region
        //////新增编辑字段,活动手机内容
        ///修改人  穆凤凤
        ///修改时间 2012-4-26
        ///endRegion
        info.PhoneDetail = PhoneDetail.Text;//mff
        info.Detail = content.Text;
        info.Education = Education.Text;
        ///Region
        //////新增编辑字段,活动的显示顺序
        ///修改人  穆凤凤
        ///修改时间 2012-3-29
        ///endRegion
        if(string.IsNullOrEmpty(TextBox_order.Text)){info.Order=null;}
        else{info.Order=int.Parse(TextBox_order.Text);}
        info.IsHot = hot_rbt.SelectedItem.Selected;
        info.IsRecommendation = recom_rbt.SelectedValue == "0" ? false : true;
        info.IsHomepageTop = indextop.SelectedValue == "0" ? false : true;
        info.IsColumnTop = columntop.SelectedValue == "0" ? false : true;
        info.ColumnID = int.Parse(ViewState[VIEWSTATE_COLUMN_ID].ToString());
        info.LayerIDs = ViewState[VIEWSTATE_LAYER_ID].ToString();
        info.State = int.Parse(pub.SelectedValue);
        info.ListImg = string.IsNullOrEmpty(filename) ? ViewState[VIEWSTATE_IMG_LIST].ToString() : filename;
        info.TopImg = string.IsNullOrEmpty(topImgName) ? ViewState[VIEWSTATE_IMG_TOP].ToString() : topImgName;
        info.TemplateID = int.Parse(templateId.SelectedValue);
        info.EventPhone = phoneEvent.Text;   //为手机活动标题赋值
        info.PhoneVenue = txtPhoneVenue.Text;  //为手机活动地点赋值


        info.TicketUrl = txtTicketUrl.Text;
        info.VenueImagePath = string.IsNullOrEmpty(venueMapFileName) ? ViewState[VIEWSTATE_IMG_TOP].ToString() : venueMapFileName;
        info.IsSeriesMain = chkIsSeriesMain.Checked;
        info.SeriesMainEventsID = null;
        if (!string.IsNullOrEmpty(ddlSeries.SelectedValue))
            info.SeriesMainEventsID = int.Parse(ddlSeries.SelectedValue);

        List<string> weekList = new List<string>();
        if (this.Monday.Checked) weekList.Add("1");
        if (this.Tuesday.Checked) weekList.Add("2");
        if (this.Wednesday.Checked) weekList.Add("3");
        if (this.Thursday.Checked) weekList.Add("4");
        if (this.Friday.Checked) weekList.Add("5");
        if (this.Saturday.Checked) weekList.Add("6");
        if (this.Sunday.Checked) weekList.Add("7");
        JoinedString str = new JoinedString(weekList.ToArray(), ",");

        info.Week = str.ToString();
        info.ShowTime = this.txtShowTime.Text;
        if (upLoadHtmlName != null)
        {
            info.UpLoadHtmlName = upLoadHtmlName;
        }
        else
        {
            if (!string.IsNullOrEmpty(ViewState[VIEWSTATE_EVENT_ID].ToString()))
            {
                EventsModel info1 = new EventsBLL(this.LangID).selEvent(int.Parse(ViewState[VIEWSTATE_EVENT_ID].ToString()));
                info.UpLoadHtmlName = info1.UpLoadHtmlName;
            }

        }
        info.AllowUploadAttachToComment = chkAllowUpload.Checked;

        ResultInfo res=bll.Save(info);

        if (res.Result && isok)
        {
            string sid = ddlSeries.SelectedValue;
            if (!string.IsNullOrEmpty(sid) && synMedia.Checked)
            {
                EventsModel srcEventsModel = new EventsModel();
                srcEventsModel.LanguageID = info.LanguageID;
                srcEventsModel.ID = int.Parse(sid);

                bll.SyncEventsAttachments(srcEventsModel, info);
            }

            EventsDateModel eDModel = new EventsDateModel();
            eDModel.ID = ((EventsModel)res.ReturnObject).ID;
            eDModel.LanguageID = info.LanguageID;
            eDBll.Dele((int)eDModel.ID);
            if ((info.StartTime == null || info.EndTime == null))
            {
                if (info.StartTime == null && info.EndTime != null)
                {
                    eDModel.Time = ((DateTime)((EventsModel)res.ReturnObject).EndTime).ToString("yyyy-MM-dd");
                    ResultInfo eDRes = eDBll.Save(eDModel);
                }
                if (info.EndTime == null && info.StartTime != null)
                {
                    eDModel.Time = ((DateTime)((EventsModel)res.ReturnObject).StartTime).ToString("yyyy-MM-dd");
                    ResultInfo eDRes = eDBll.Save(eDModel);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(info.Week))
                {
                    if (info.EndTime == null && info.StartTime != null)
                    {
                        eDModel.Time = ((DateTime)((EventsModel)res.ReturnObject).StartTime).ToString("yyyy-MM-dd");
                        ResultInfo eDRes = eDBll.Save(eDModel);
                    }

                    if (info.EndTime != null && info.StartTime == null)
                    {
                        eDModel.Time = ((DateTime)((EventsModel)res.ReturnObject).EndTime).ToString("yyyy-MM-dd");
                        ResultInfo eDRes = eDBll.Save(eDModel);
                    }

                    if (info.EndTime != null && info.StartTime != null)
                    {
                        eDModel.Time = ((DateTime)((EventsModel)res.ReturnObject).StartTime).ToString("yyyy-MM-dd");
                        ResultInfo eDRes = eDBll.Save(eDModel);
                        //处理循环多插入一天的问题 2012-5-14 李学明
                        var comenddate = info.EndTime;
                        if(info.EndTime.Value.Hour>0|| info.EndTime.Value.Minute>0||info.EndTime.Value.Second>0)
                        {
                            comenddate = info.EndTime.Value.AddDays(-1);
                        }


                        while (info.StartTime < comenddate)
                        {
                            //DateTime time = (DateTime)((EventsModel)res.ReturnObject).StartTime;
                            //time = time.AddDays(1);
                            info.StartTime = ((DateTime)(info.StartTime)).AddDays(1);
                            eDModel.Time = ((DateTime)(info.StartTime)).ToString("yyyy-MM-dd");
                            ResultInfo eDResu = eDBll.Save(eDModel);
                        }
                    }

                }
                else
                {
                    if (info.EndTime != null && info.StartTime != null)
                    {
                        DayOfWeek week;
                        string[] weeks = info.Week.Split(',');
                        for (int i = 0; i < weeks.Length; i++)
                        {

                            switch (weeks[i])
                            {
                                case "1":
                                    week = DayOfWeek.Monday;
                                    CheckWeeK((DateTime)info.StartTime, (DateTime)info.EndTime, week, eDModel);
                                    break;
                                case "2":
                                    week = DayOfWeek.Tuesday;
                                    CheckWeeK((DateTime)info.StartTime, (DateTime)info.EndTime, week, eDModel);
                                    break;
                                case "3":
                                    week = DayOfWeek.Wednesday;
                                    CheckWeeK((DateTime)info.StartTime, (DateTime)info.EndTime, week, eDModel);
                                    break;
                                case "4":
                                    week = DayOfWeek.Thursday;
                                    CheckWeeK((DateTime)info.StartTime, (DateTime)info.EndTime, week, eDModel);
                                    break;
                                case "5":
                                    week = DayOfWeek.Friday;
                                    CheckWeeK((DateTime)info.StartTime, (DateTime)info.EndTime, week, eDModel);
                                    break;
                                case "6":
                                    week = DayOfWeek.Saturday;
                                    CheckWeeK((DateTime)info.StartTime, (DateTime)info.EndTime, week, eDModel);
                                    break;
                                case "7":
                                    week = DayOfWeek.Sunday;
                                    CheckWeeK((DateTime)info.StartTime, (DateTime)info.EndTime, week, eDModel);
                                    break;
                            }

                        }

                    }

                }
            }
            Response.Redirect("event_list.aspx?columnid=" + ViewState[VIEWSTATE_COLUMN_ID] + "&layerid=" +
                              ViewState[VIEWSTATE_LAYER_ID] + "&langID=" + LangID + "&isSpecial =" +
                              Request.QueryString["IsSpecial"]);
        }
        else
        {
            if (erro == "")
            {
                Response.Write("<script>alert('保存失败')</script>");

                Response.Write(res.Message);
            }
            else
            {
                Response.Write(String.Format("<script>alert('{0}')</script>", erro));
            }

        }

    }

    protected void ddlSeries_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sEventsID = ddlSeries.SelectedValue;
        if (string.IsNullOrEmpty(sEventsID)) return;

        int eventsID = int.Parse(sEventsID);
        InitPage(eventsID, 1);
    }

    protected void chkIsSeriesMain_CheckedChanged(object sender, EventArgs e)
    {

    }
    protected void lbBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("event_list.aspx?columnid=" + ViewState[VIEWSTATE_COLUMN_ID] + "&layerid=" +
                          ViewState[VIEWSTATE_LAYER_ID] + "&langID=" + LangID + "&isSpecial =" +
                          Request.QueryString["IsSpecial"]);
    }

    private void CheckWeeK(DateTime staTime, DateTime endTime, DayOfWeek week, EventsDateModel model)
    {
        TimeSpan tSpan = new TimeSpan(endTime.Ticks - staTime.Ticks);
        for (int i = 0; i <= tSpan.TotalDays; i++)
        {
            if (staTime.AddDays(i).DayOfWeek == week)
            {
                model.Time = staTime.AddDays(i).ToString("yyyy-MM-dd");
                EventDateBLL eDBll = new EventDateBLL(this.LangID);
                ResultInfo eDResu = eDBll.Save(model);
            }
        }
    }
}